<template>
	<div class="app-container">
		<el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px" label-position="left">
			<el-form-item label="借阅单号" prop="borrowNumber">
				<el-input v-model="queryParams.borrowNumber" placeholder="请输入借阅单号" clearable @keyup.enter="handleQuery" />
			</el-form-item>
			<el-form-item label="借阅人" prop="userName">
				<el-input v-model="queryParams.userName" placeholder="请输入借阅人姓名" clearable @keyup.enter="handleQuery" />
			</el-form-item>
			<el-form-item label="借阅人身份证" prop="userIdentity">
				<el-input v-model="queryParams.userIdentity" placeholder="请输入借阅人身份证" clearable @keyup.enter="handleQuery" />
			</el-form-item>
			<el-form-item label="借阅类型" prop="borrowType">
				<el-select v-model="queryParams.borrowType" placeholder="请选择借阅类型" clearable>
					<el-option v-for="dict in borrow_type" :key="dict.value" :label="dict.label" :value="dict.value" />
				</el-select>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
				<el-button icon="Refresh" @click="resetQuery">重置</el-button>
			</el-form-item>
		</el-form>

		<el-row :gutter="10" class="mb8">
			<el-col :span="1.5">
				<el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['borrow:borrow:add']">新增</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate" v-hasPermi="['borrow:borrow:edit']">修改</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete" v-hasPermi="['borrow:borrow:remove']">删除</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['borrow:borrow:export']">导出</el-button>
			</el-col>
			<right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
		</el-row>

		<el-table v-loading="loading" :data="borrowList" @selection-change="handleSelectionChange">
			<el-table-column type="selection" width="55" align="center" />
			<el-table-column label="借阅单号" align="center" prop="borrowNumber" />
			<el-table-column label="借阅人" align="center" prop="userName" />
			<!-- <el-table-column label="借阅人电话" align="center" prop="userPhone" />
      <el-table-column label="借阅人身份证" align="center" prop="userIdentity" /> -->
			<!-- <el-table-column label="借阅目的" align="center" prop="borrowReason" /> -->
			<el-table-column label="申请日期" align="center" prop="planBorrowDate" width="180">
				<template #default="scope">
					<span>{{ parseTime(scope.row.planBorrowDate, '{y}-{m}-{d}') }}</span>
				</template>
			</el-table-column>
			<el-table-column label="预计归还日期" align="center" prop="planBackDate" width="180">
				<template #default="scope">
					<span :style="{ color: isReturnLate(scope.row.planBackDate,scope.row.status) ? 'red': ''}">{{ parseTime(scope.row.planBackDate, '{y}-{m}-{d}') }}</span>
				</template>
			</el-table-column>
			<el-table-column label="状态" align="center" prop="status">
				<template #default="scope">
					<dict-tag :options="borrow_status" :value="scope.row.status" />
				</template>
			</el-table-column>

			<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
				<template #default="scope">
					<!-- 待审批状态，可以修改，删除-->
					<el-button type="text" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['borrow:borrow:edit']" v-if="scope.row.status == 0">修改</el-button>
					<el-button type="text" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['borrow:borrow:remove']" v-if="scope.row.status == 0">删除</el-button>
					<el-button type="text" icon="Info" @click="handleDetail(scope.row)" v-hasPermi="['borrow:borrow:detail']" v-if="scope.row.status !=0">查看
					</el-button>
					<el-button type="text" icon="info" @click="handleReturn(scope.row)" v-hasPermi="['borrow:borrow:return']" v-if="scope.row.status == 3">归还
					</el-button>
				</template>
			</el-table-column>
		</el-table>

		<pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
		 @pagination="getList" />

		<!-- 添加或修改借阅对话框 -->
		<el-dialog :title="title" v-model="open" width="1000px">
			<el-form ref="borrowRef" :model="form" :rules="rules" label-width="90px" :inline="true">
				<el-form-item label="借阅人" prop="borrowUserId">
					<el-cascader v-model="form.borrowUserId" :props="userOptions" :placeholder="form.userName" :show-all-levels="false">
					</el-cascader>
				</el-form-item>
				<el-form-item label="借阅目的" prop="borrowReason">
					<el-input v-model="form.borrowReason" placeholder="请输入借阅目的" />
				</el-form-item>
				<el-form-item label="申请日期" prop="planBorrowDate">
					<el-date-picker clearable v-model="form.planBorrowDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择申请日期">
					</el-date-picker>
				</el-form-item>
				<el-form-item label="预计归还日期" prop="planBackDate">
					<el-date-picker clearable v-model="form.planBackDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择预计归还日期">
					</el-date-picker>
				</el-form-item>
				<el-form-item label="借阅类型" prop="borrowType">
					<el-select v-model="form.borrowType" placeholder="请选择借阅类型">
						<el-option v-for="dict in borrow_type" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
					</el-select>
				</el-form-item>
				<el-divider content-position="center">借阅详情信息</el-divider>
				<el-row :gutter="10" class="mb8">
					<el-col :span="1.5">
						<el-button type="primary" icon="Plus" @click="handleAddArcBorrowDetails">添加</el-button>
					</el-col>
					<el-col :span="1.5">
						<el-button type="danger" icon="Delete" @click="handleDeleteArcBorrowDetails">删除</el-button>
					</el-col>
				</el-row>
				<el-table :data="arcBorrowDetailsList" :row-class-name="rowArcBorrowDetailsIndex" @selection-change="handleArcBorrowDetailsSelectionChange"
				 ref="arcBorrowDetails">
					<el-table-column type="selection" width="50" align="center" />
					<el-table-column label="序号" align="center" prop="index" width="50" />
					<el-table-column label="档案号" prop="archiveCode" width="240" />
					<el-table-column label="题名" prop="archiveTitle" width="240" />
					<el-table-column label="密级" prop="archiveSecretLevel" width="240">
						<template #default="scope">
							<dict-tag :options="secret_level" :value="scope.row.archiveSecretLevel" />
						</template>
					</el-table-column>
				</el-table>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" @click="submitForm">确 定</el-button>
					<el-button @click="cancel">取 消</el-button>
				</div>
			</template>
			<el-dialog title="选择档案" v-model="arcOpen" width="1000px">
				<select-arc @submit="selectArcSubmit" @cancel="selectArcCancel"></select-arc>
			</el-dialog>
		</el-dialog>
		<el-dialog title="借阅详情" v-model="detailOpen" width="1000px">
			<BorrowDetail :borrowId="borrowId"></BorrowDetail>
		</el-dialog>
		<el-dialog title="借阅归还" v-model="returnOpen" width="1000px">
			<el-form ref="returnRef" :model="returnForm" label-width="90px">
				<el-form-item label="归还日期" prop="returnDate">
					<el-date-picker :clearable="false" v-model="returnForm.returnDate" type="date" value-format="YYYY-MM-DD">
					</el-date-picker>
				</el-form-item>
				<el-form-item label="备注" prop="returnRemark">
					<el-input v-model="returnForm.returnRemark" placeholder="" />
				</el-form-item>
				<el-table :data="arcBorrowDetailsList" :row-class-name="rowArcBorrowDetailsIndex" @selection-change="handleArcBorrowDetailsSelectionChange"
				 ref="dataReturn">
					<el-table-column type="selection" width="50" align="center" />
					<el-table-column label="序号" align="center" prop="index" width="50" />
					<el-table-column label="档案号" prop="archiveCode" width="240" />
					<el-table-column label="题名" prop="archiveTitle" width="240" />
					<el-table-column label="密级" prop="archiveSecretLevel" width="240">
						<template #default="scope">
							<dict-tag :options="secret_level" :value="scope.row.archiveSecretLevel" />
						</template>
					</el-table-column>
				</el-table>

			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" @click="submitReturn">确 定</el-button>
					<el-button @click="cancelReturn">取 消</el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>

<script setup name="Borrow">
	import {
		listDept
	} from "@/api/system/dept"
	import {
		listUser
	} from "@/api/system/user"
	import {
		listBorrow,
		getBorrow,
		delBorrow,
		addBorrow,
		updateBorrow,
		returnBorrow
	} from "@/api/borrow/borrow";

	import SelectArc from '@/components/Dialog/SelectArc'
	import BorrowDetail from '@/views/borrow/borrow/detail'
	import {
		onMounted,
		reactive,
		toRef
	} from "vue";

	const {
		proxy
	} = getCurrentInstance();
	const {
		return_status,
		is_return,
		borrow_type,
		is_delflag,
		borrow_status,
		is_confirm,
		secret_level
	} = proxy.useDict('return_status', 'is_return', 'borrow_type', 'is_delflag', 'borrow_status', 'is_confirm',
		'secret_level');

	const borrowList = ref([]);
	const arcBorrowDetailsList = ref([]);
	const open = ref(false);
	const loading = ref(true);
	const showSearch = ref(true);
	const ids = ref([]);
	const checkedArcBorrowDetails = ref([]);
	const single = ref(true);
	const multiple = ref(true);
	const total = ref(0);
	const title = ref("");
	const arcOpen = ref(false);
	const detailOpen = ref(false); // 详情弹窗
	const returnOpen = ref(false); // 归还弹窗
	const borrowId = ref(0);
	const defaultDate = ref('2020-07-07')

	// 是否已经超过归还日期
	function isReturnLate(planBackDate, status) {
		var backDate = new Date(Date.parse(planBackDate))
		var nowDate = new Date()

		// 借阅中或部分归还状态 提示红色
		if (nowDate > backDate && (status == 3 || status == 4)) {
			return true
		} else {
			return false
		}
	}

	// 部门列表
	var deptList = [];
	/** 查询部门列表 */
	function getDeptList() {
		loading.value = true;
		listDept(queryParams.value).then(response => {
			deptList.value = proxy.handleTree(response.data, "deptId");
			loading.value = false;
		});
	}
	// 用户列表
	let id = 0
	const userOptions = {
		lazy: true,
		emitPath: false,
		lazyLoad(node, resolve) {
			const {
				level
			} = node;
			var parentId = 0;
			if (node.level != 0) {
				parentId = node.value
			}

			function createNode(parentId, resolve) {
				const nodes = deptList.filter(item => item.parentId == parentId).map((item) => ({
					value: item.deptId,
					label: item.deptName,
					leaf: false,
				}));
				// 可能是最后一级的部门，查询员工
				if (nodes.length == 0) {
					listUser({
						"deptId": parentId
					}).then(response => {
						const nodes = response.rows.map((item) => ({
							value: item.userId,
							label: item.nickName,
							leaf: true,
						}))
						resolve(nodes)
					})
				} else {
					resolve(nodes);
				}
			}

			if (parentId == 0) {
				listDept().then(response => {
					deptList = response.data;
					createNode(0, resolve)
				});
			} else {
				createNode(parentId, resolve)
			}
		}
	}


	const data = reactive({
		form: {},
		queryParams: {
			pageNum: 1,
			pageSize: 10,
			borrowNumber: null,
			userName: null,
			userIdentity: null,
			borrowType: null,
		},
		rules: {
			borrowNumber: [{
				required: true,
				message: "借阅单号不能为空",
				trigger: "blur"
			}],
			userName: [{
				required: true,
				message: "借阅人不能为空",
				trigger: "blur"
			}],
			borrowReason: [{
				required: true,
				message: "借阅目的不能为空",
				trigger: "blur"
			}],
			planBackDate: [{
				required: true,
				message: "预计归还日期不能为空",
				trigger: "blur"
			}],
		},
		returnForm: {},
	});

	const {
		queryParams,
		form,
		rules,
		returnForm
	} = toRefs(data);


	/** 查询借阅列表 */
	function getList() {
		loading.value = true;
		listBorrow(queryParams.value).then(response => {
			borrowList.value = response.rows;
			total.value = response.total;
			loading.value = false;
		});
	}

	// 取消按钮
	function cancel() {
		open.value = false;
		reset();
	}

	// 表单重置
	function reset() {
		form.value = {
			borrowId: null,
			borrowNumber: null,
			borrowUserId: null,
			userName: null,
			borrowReason: null,
			planBorrowDate: null,
			planBackDate: null,
			updateTime: null,
			delflag: null,
			status: null,
			detailDataIndex: null,
			isReturn: null,
			approvalOpinions: null,
			borrowType: null,
			isConfirm: null
		};
		var now = new Date()
		var nowDate = now.getFullYear() + '-' + ((now.getMonth() + 1) >= 10 ? (now.getMonth() + 1) : '0' + (now.getMonth() +
			1)) + '-' + (now.getDate() >= 10 ? now.getDate() : '0' + now.getDate())
		console.log(nowDate)
		returnForm.value = {
			returnDate: nowDate,
			returnRemark: null
		};
		arcBorrowDetailsList.value = [];
		proxy.resetForm("borrowRef");
		proxy.resetForm("returnRef");
	}

	/** 搜索按钮操作 */
	function handleQuery() {
		queryParams.value.pageNum = 1;
		getList();
	}

	/** 重置按钮操作 */
	function resetQuery() {
		proxy.resetForm("queryRef");
		handleQuery();
	}

	// 多选框选中数据
	function handleSelectionChange(selection) {
		ids.value = selection.map(item => item.borrowId);
		single.value = selection.length != 1;
		multiple.value = !selection.length;
	}

	/** 新增按钮操作 */
	function handleAdd() {
		reset();
		open.value = true;
		title.value = "添加借阅";
	}

	/** 修改按钮操作 */
	function handleUpdate(row) {
		reset();
		const borrowId = row.borrowId || ids.value
		getBorrow(borrowId).then(response => {
			console.log(response.data)
			form.value = response.data;

			arcBorrowDetailsList.value = response.data.arcBorrowDetailsList;
			open.value = true;
			title.value = "修改借阅";
		});
	}

	/** 提交按钮 */
	function submitForm() {
		proxy.$refs["borrowRef"].validate(valid => {
			if (valid) {
				form.value.arcBorrowDetailsList = arcBorrowDetailsList.value;
				if (form.value.borrowId != null) {
					updateBorrow(form.value).then(response => {
						proxy.$modal.msgSuccess("修改成功");
						open.value = false;
						getList();
					});
				} else {
					addBorrow(form.value).then(response => {
						proxy.$modal.msgSuccess("新增成功");
						open.value = false;
						getList();
					});
				}
			}
		});
	}
	/** 归还确定按钮 */
	function submitReturn() {
		if (checkedArcBorrowDetails.value.length == 0) {
			proxy.$modal.msgError("请先选择要归还的档案");
		} else {
			const arcBorrowDetailss = arcBorrowDetailsList.value;
			const checkedArcBorrowDetailss = checkedArcBorrowDetails.value;
			const checkedIds = arcBorrowDetailss.filter(function(item) {
				return checkedArcBorrowDetailss.indexOf(item.index) != -1
			}).map(item => item.detailId);
			returnForm.value['borrowId'] = borrowId
			returnForm.value['detailIds'] = checkedIds


			returnBorrow(returnForm.value).then(response => {
				proxy.$modal.msgSuccess("归还成功");
			})
		}
	}

	function cancelReturn() {
		returnOpen.value = false
	}


	/** 删除按钮操作 */
	function handleDelete(row) {
		const borrowIds = row.borrowId || ids.value;
		proxy.$modal.confirm('是否确认删除借阅编号为"' + borrowIds + '"的数据项？').then(function() {
			return delBorrow(borrowIds);
		}).then(() => {
			getList();
			proxy.$modal.msgSuccess("删除成功");
		}).catch(() => {});
	}

	/** 查看详情操作 */
	function handleDetail(row) {
		reset();

		detailOpen.value = true;
		borrowId.value = row.borrowId || ids.value;
	}
	/** 归还 */
	function handleReturn(row) {
		reset();
		borrowId.value = row.borrowId || ids.value
		getBorrow(borrowId.value).then(response => {
			form.value = response.data;

			arcBorrowDetailsList.value = response.data.arcBorrowDetailsList;
			returnOpen.value = true;
			// 默认全部选中
			nextTick(() => {
				proxy.$refs["dataReturn"].toggleAllSelection()
			});
		})
	}


	/** 借阅详情序号 */
	function rowArcBorrowDetailsIndex({
		row,
		rowIndex
	}) {
		row.index = rowIndex + 1;
	}

	/** 借阅详情添加按钮操作 */
	function handleAddArcBorrowDetails() {
		// 选择档案
		arcOpen.value = true;

		// let obj = {};
		// obj.archiveId = "";
		// obj.realBorrowTime = "";
		// obj.realBackTime = "";
		// obj.status = "";
		// arcBorrowDetailsList.value.push(obj);



	}

	/** 借阅详情删除按钮操作 */
	function handleDeleteArcBorrowDetails() {
		if (checkedArcBorrowDetails.value.length == 0) {
			proxy.$modal.msgError("请先选择要删除的借阅详情数据");
		} else {
			const arcBorrowDetailss = arcBorrowDetailsList.value;
			const checkedArcBorrowDetailss = checkedArcBorrowDetails.value;
			arcBorrowDetailsList.value = arcBorrowDetailss.filter(function(item) {
				return checkedArcBorrowDetailss.indexOf(item.index) == -1
			});
		}
	}

	/** 复选框选中数据 */
	function handleArcBorrowDetailsSelectionChange(selection) {
		checkedArcBorrowDetails.value = selection.map(item => item.index)
	}

	/** 导出按钮操作 */
	function handleExport() {
		proxy.download('borrow/borrow/export', {
			...queryParams.value
		}, `borrow_${new Date().getTime()}.xlsx`)
	}

	function selectArcSubmit(archiveList) {

		var noAddList = [];
		var added = false;
		// 判断是否已经添加过
		for (var i = 0; i < archiveList.length; i++) {
			added = false;
			for (var y = 0; y < arcBorrowDetailsList.value.length; y++) {
				if (archiveList[i].archiveCode == arcBorrowDetailsList.value[y].archiveCode) {
					added = true;
					break;
				}
			}
			if (!added) {
				noAddList.push(archiveList[i])
			}
		}

		noAddList.map(item => {
			let obj = {};
			obj.archiveId = item.archiveId;
			obj.archiveCode = item.archiveCode;
			obj.archiveTitle = item.titleName;
			obj.archiveSecretLevel = item.secretLevel;

			arcBorrowDetailsList.value.push(obj);
		})


		// let obj = {};
		// obj.archiveId = "";
		// obj.realBorrowTime = "";
		// obj.realBackTime = "";
		// obj.status = "";
		// arcBorrowDetailsList.value.push(obj);


		arcOpen.value = false;
	}

	function selectArcCancel(text) {
		arcOpen.value = false;
	}


	getList();
</script>
